<!--
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2019-10-30 21:29:17
 * @LastEditors  : cxguo
 * @LastEditTime : 2019-12-26 17:21:07
 -->
<template>
  <div>
    <!-- specsTabData: {{ specsTabData }} -->
    <el-button v-if="isShowCopybtn" size="small" type="primary" @click="btnBatchCopyPrice">
      按照( {{ tabDefaultName }} )批量复制
    </el-button>
    <el-tabs v-model="tabName">
      <el-tab-pane
        v-for="(specsObj,index) in specsTabData"
        :key="specsObj.label"
        :name="specsObj.label"
      >
        <span slot="label">{{ specsObj.label }}</span>
        <vxe-grid
          :ref="`table-${index}`"
          :key="index"
          class="grid"
          border
          size="small"
          resizable
          highlight-hover-row
          :edit-config="{trigger: 'click', mode: 'row'}"
          :columns="columnsData"
          :data="specsObj.priceData"
        />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script>
import { oftenuse } from '@/libs/mixins'
import clonedeep from 'clonedeep'
import { specs } from './mixins'

export default {
  name: 'GoodPrice',
  mixins: [oftenuse, specs],
  props: {
    /**
     * 单位数据
     */
    unitData: {
      type: Array,
      default: () => { return [] }
    },
    /**
     * 已经选择的规格数据
     */
    selectSpecsData: {
      type: Array,
      default: () => { return [] }
    }
  },
  data() {
    return {
      comps: {},
      tabName: null,
      tabDefaultName: null,
      specsTabData: [],
      originColumnsData: [
        { field: 'priceType', width: 150,
          title: '价格分类'
        }
      ],
      // 0 出 1 进
      priceType: [
        { value: '1', label: '零售价', cat: '0' },
        { value: '2', label: '批发价', cat: '0' },
        { value: '3', label: '最低售价', cat: '0' },
        { value: '4', label: '参考进价', cat: '1' }
      ],
      ruleValidator: { }
    }
  },
  computed: {
    isShowCopybtn: function() {
      return this.specsTabData.length !== 1
    },
    columnsData: function() {
      const originColumnsData = this.originColumnsData
      const unitPriceCols = []
      const unitData = this.unitData || []
      unitData.forEach(item => {
        const title = `价格/${item.label}`
        const colObj = {
          field: item.label, title,
          editRender: { name: 'ElInputNumber', props: { size: 'mini' }},
          width: 200
        }
        unitPriceCols.push(colObj)
      })
      return [...originColumnsData, ...unitPriceCols]
    },
    /**
     * 价格表的数据
     */
    priceData: function() {
      const priceType = this.priceType
      const result = []
      priceType.forEach(item => {
        const data = this.getPriceTableDataByCols(this.columnsData || [])
        const obj = Object.assign(data, { priceType: item.label, priceCat: item.cat })
        result.push(obj)
      })
      return result
    },
    /**
     * tab所有的价格数据
     */
    specsTabDataComputed: function() {
      const specsData = this.getSpecsNameData(this.spTableData)
      const priceData = this.priceData
      const result = []
      specsData.forEach((val, i) => {
        const obj = { value: i, label: val, priceData: clonedeep(priceData) }
        result.push(obj)
      })
      return result
    },
    pricePostData: function() {
      const specsTabData = this.specsTabData
      const result = []
      specsTabData.forEach(item => {
        const onespecPriceData = this.getOneSpecPriceData(item)
        result.push(onespecPriceData)
      })
      return result
    }
  },
  watch: {
    'specsTabDataComputed': {
      handler(data) {
        if (!data.length) return null
        const tabDefaultName = data[0].label
        this.tabName = this.tabDefaultName = tabDefaultName
        this.specsTabData = data
      },
      immediate: true,
      deep: true
    }
  },
  created() {
  },
  mounted() {
    this.$set(this.comps, 'table', this.$refs.table)
  },
  methods: {
    btnGetPrice() {
      const price = this.getPriceData()
      console.log('最新价格：', price)
    },
    btnBatchCopyPrice() {
      try {
        this.batchCopyPrice()
        this.$message.success('复制成功！')
      } catch (error) {
        console.log(error)
        this.$message.error(`复制失败:${error.message}`)
      }
    },
    // api
    /**
     * 获取不同规格价格最终数据
     */
    getPriceTableData() {
      return this.specsTabData
    },
    batchCopyPrice() {
      const specsTabData = this.specsTabData
      const tempData = specsTabData[0].priceData
      specsTabData.forEach(item => {
        this.copyPriceAttrs(item.priceData, tempData)
      })
    },
    copyPriceAttrs(priceData, tempData) {
      priceData.forEach((obj, i) => {
        Object.keys(obj).forEach(key => {
          if (!['priceType', '_XID'].includes(key)) {
            this.$set(obj, key, tempData[i][key])
          }
        })
      })
    },
    getPriceTableDataByCols(columnsData) {
      const result = {}
      columnsData.forEach(item => {
        if (item.hasOwnProperty('field')) {
          result[item.field] = 0
        }
      })
      return result
    },
    /**
     * 获取specs数据的Name
     * @param {已经选择的规格数据} specsData
     */
    getSpecsNameData(specsData) {
      if (!specsData) return []
      const result = []
      specsData.forEach(item => {
        let name = ''
        Object.keys(item).forEach((key, i) => {
          if (i === 0) name += `${item[key]}`
          else name += `-${item[key]}`
        })
        result.push(name)
      })
      return result
    },
    /**
     * 获取一个规格的价格数据
     */
    getOneSpecPriceData(oneSpecPriceData) {
      const priceData = oneSpecPriceData.priceData
      const unitData = this.unitData || []
      const result = []
      unitData.forEach(item => {
        const unitId = `${item.value}`
        const price = this.getUnitPrice(priceData, item.label)
        const obj = { unitId, ...price }
        result.push(obj)
      })
      return result
    },
    getUnitPrice(priceData, unit) {
      const pricePurchase = {}
      const priceSale = {}
      priceData.forEach(item => {
        if (item.priceCat === '0') {
          priceSale[item.priceType] = item[unit]
        }
        if (item.priceCat === '1') {
          pricePurchase[item.priceType] = item[unit]
        }
      })
      const result = {
        pricePurchase: JSON.stringify(pricePurchase),
        priceSale: JSON.stringify(priceSale)
      }
      return result
    }
  }
}
</script>
